<?php

namespace app\enterprise\controller;

use app\enterprise\controller\Enterprise; // 基础控制器
use app\enterprise\model\User as UserModel;
use think\Request;
use think\facade\Db; // 用于直接数据库查询和事务处理

// 模型导入
use app\model\plan\PlanStaff;
use app\enterprise\model\plan\StudyCourse;
use app\enterprise\model\staff\Staff;
use app\model\plan\Plan;
use app\model\plan\exam\StaffExam;
use app\model\exam\Exam;
use app\model\snap\Snap; // 基于sj_snap表的模型
use app\model\course\Courseware; // 课件模型
use app\enterprise\model\company\Company; // 公司模型
use app\model\plan\PlanCourse;
use app\model\course\course\Course;
use app\model\teacher\Teacher; // 教师模型


class ArchiveController extends Enterprise
{
    // 辅助函数：将时间戳格式化为YYYY-MM-DD HH:MM:SS或其他格式
    private function formatDate($timestamp, $format = 'Y-m-d')
    {
        // 确保时间戳是有效数字
        $timestamp = filter_var($timestamp, FILTER_VALIDATE_INT) === false ? 0 : (int)$timestamp;
        return $timestamp > 0 ? date($format, $timestamp) : '';
    }

    // 辅助函数：将时间戳格式化为YYYY年MM月DD日
    private function formatDateChinese($timestamp)
    {
        // 确保时间戳是有效数字
        $timestamp = filter_var($timestamp, FILTER_VALIDATE_INT) === false ? 0 : (int)$timestamp;
        return $timestamp > 0 ? date('Y年m月d日', $timestamp) : '';
    }

    // 辅助函数：根据身份证号计算年龄
    private function calculateAge($idcard)
    {
        if (empty($idcard) || (strlen($idcard) != 15 && strlen($idcard) != 18)) {
            return '';
        }
        // 此处逻辑不变，因为主要处理字符串
        $yearBirth = strlen($idcard) == 18 ? substr($idcard, 6, 4) : ('19' . substr($idcard, 6, 2));
        $monthBirth = strlen($idcard) == 18 ? substr($idcard, 10, 2) : substr($idcard, 8, 2);
        $dayBirth = strlen($idcard) == 18 ? substr($idcard, 12, 2) : substr($idcard, 10, 2);
        
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay = date('d');
        
        $age = (int)$currentYear - (int)$yearBirth;
        if ((int)$currentMonth < (int)$monthBirth || ((int)$currentMonth == (int)$monthBirth && (int)$currentDay < (int)$dayBirth)) {
            $age--;
        }
        return $age >= 0 ? $age : '';
    }
    
    // 辅助函数：根据参数ID获取参数名称
    private function getParameterNameById($paraId, &$allParams)
    {
        $paraId = filter_var($paraId, FILTER_VALIDATE_INT) === false ? 0 : (int)$paraId;
        return isset($allParams[$paraId]) ? $allParams[$paraId]['para_name'] : '未知';
    }

    // 辅助函数：根据课件信息确定类型
    private function getCoursewareType($coursewareDetail)
    {
        // 如果有video_url，通常是视频类型
        if (!empty($coursewareDetail['video_url'])) {
            return '视频';
        }
        
        // 根据文件扩展名判断类型（如果有的话）
        $videoUrl = $coursewareDetail['video_url'] ?? '';
        if (!empty($videoUrl)) {
            $extension = strtolower(pathinfo($videoUrl, PATHINFO_EXTENSION));
            switch ($extension) {
                case 'mp4':
                case 'avi':
                case 'mov':
                case 'wmv':
                case 'flv':
                    return '视频';
                case 'pdf':
                    return 'PDF文档';
                case 'doc':
                case 'docx':
                    return 'Word文档';
                case 'ppt':
                case 'pptx':
                    return 'PPT演示';
                default:
                    return '视频'; // 默认为视频
            }
        }
        
        return '视频'; // 默认类型
    }

    /**
     * 获取人员培训档案详情
     * GET enterprise/archive/training_record
     * @param Request $request
     * @return \think\Response
     */
    public function getTrainingRecord(Request $request)
    {
        // 获取并验证计划人员ID
        $plan_staff_id = intval($request->param('plan_staff_id', 0));
        if (empty($plan_staff_id) || $plan_staff_id <= 0) {
            return app('json')->fail('计划人员ID (plan_staff_id) 无效');
        }

        // 查询计划人员记录
        $planStaff = PlanStaff::find($plan_staff_id);
        if (!$planStaff) {
            return app('json')->fail('未找到指定的培训人员记录');
        }
        $study_ourses = StudyCourse::where(['status' => 1, 'plan_staff_id' => $plan_staff_id])->select()->toArray();
        $studied_hours = '';
        if (!empty($study_ourses)) {
            $studied_hours = array_sum(array_column($study_ourses, 'courseware_hour'));
        }

        // 获取计划ID和人员ID
        $plan_id = $planStaff->plan_id;
        $staff_id = $planStaff->staff_id;
        $archiveData = [];

        // 预加载所有参数，提高效率
        $allParameters = Db::table('sj_parameter')->where('status', 1)->column('*', 'id');

        // --- 基本信息 --- 
        $staffInfo = Staff::find($staff_id);
        // 当前学员的企业
        $archiveData['staff_company_name'] = '';
        if ( !empty($staffInfo->creator_id) ) {
            $user_info = UserModel::where('id', $staffInfo->creator_id)->with('company')->find();
            $archiveData['staff_company_name'] = $user_info->company->company_name;
        }

        $companyName = '';
        if ($staffInfo && $staffInfo->company_id) {
            $companyData = Db::table('sj_company')->where('id', $staffInfo->company_id)->find();
            if ($companyData) {
                $companyName = $companyData['company_name'];
            }
        }
        $departmentName = '';
        if($staffInfo && $staffInfo->department_id){
            $departmentData = Db::table('sj_deparment')->where('id', $staffInfo->department_id)->find();
            if($departmentData){
                $departmentName = $departmentData['department_name'];
            }
        }

        $archiveData['file_number'] = $planStaff->code; // 档案编号（使用原code字段）
        $archiveData['generation_date'] = $this->formatDateChinese(time());
        $archiveData['platform_name'] = ''; // 设置为空字符串，由用户打印后填写

        // 安全处理视频学习时长
        $rawVideoStudyDuration = $planStaff->video_study_duration ?? '0';
        $videoStudyDurationSeconds = filter_var($rawVideoStudyDuration, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) ?? 0.0;
        $cumulativeHours = $videoStudyDurationSeconds > 0 ? $videoStudyDurationSeconds / 3600 : 0.0;

        // 准备基本信息，确保staffInfo存在
        $staffName = '';
        $staffSex = 0;
        $staffTel = '';
        $staffIdCard = '';
        $staffEduId = 0;
        $staffLevelId = 0;
        $staffJobId = 0;
        $staffCreateTime = 0;
        $staffAvatar = ''; // Initialize avatar here

        if ($staffInfo) {
            $staffName = $staffInfo->username ?? '';
            $staffSex = $staffInfo->sex ?? 0;
            $staffTel = $staffInfo->mobile ?? '';
            $staffIdCard = $staffInfo->idcard ?? '';
            $staffEduId = $staffInfo->edu_id ?? 0;
            $staffLevelId = $staffInfo->level_id ?? 0;
            $staffJobId = $staffInfo->job_id ?? 0;
            $staffCreateTime = $staffInfo->create_time ?? 0;
            $staffAvatar = $staffInfo->img_url ?? ''; 
        }

        $archiveData['basic_info'] = [
            'name' => $staffName,
            'gender' => ($staffSex == 1) ? '男' : (($staffSex == 2) ? '女' : '未知'),
            'age' => $this->calculateAge($staffIdCard),
            'phone' => $staffTel,
            'avatar' => $staffAvatar,
            'id_card_number' => $staffIdCard,
            'education' => $this->getParameterNameById($staffEduId, $allParameters),
            'job_title' => $this->getParameterNameById($staffLevelId, $allParameters),
            'department' => $departmentName,
            'work_type' => $this->getParameterNameById($staffJobId, $allParameters),
            'platform_registration_time' => $staffCreateTime,
//            'cumulative_hours' => number_format($cumulativeHours, 1),
            'cumulative_hours' => $studied_hours,
            'company_name' => $companyName,
        ];

        // --- 培训计划信息 ---
        $planInfo = Plan::find($plan_id);
        $studyWayText = '';
        if ($planInfo && isset($planInfo->study_way)) {
            switch ($planInfo->study_way) {
                case 1: $studyWayText = '线上'; break;
                case 2: $studyWayText = '线下'; break;
                case 3: $studyWayText = '线上+线下'; break;
                default: $studyWayText = '未知';
            }
        }
        $courseFormatText = '';
         if ($planInfo && isset($planInfo->course_type)) {
            switch ($planInfo->course_type) {
                case 1: $courseFormatText = '网络'; break;
                case 2: $courseFormatText = '面授'; break;
                case 3: $courseFormatText = '网络+面授'; break;
                default: $courseFormatText = '未知';
            }
        }
        $archiveData['is_exam'] = $planInfo->exam_status == 1 ? true : false;
        $archiveData['training_info'] = [
            'training_name' => $planInfo->plan_name ?? '',
            'training_period' => ($planInfo && $planInfo->start_time && $planInfo->end_time) ? ($this->formatDate($planInfo->start_time) . ' - 至 - ' . $this->formatDate($planInfo->end_time)) : '-',
            'study_time_range' => ($planStaff && $planStaff->study_start_time && $planStaff->study_end_time) ? date('Y-m-d', strtotime($planStaff->study_start_time)) . ' - 至 - ' . date('Y-m-d', strtotime($planStaff->study_end_time)) : '-',
            'study_method' => $studyWayText,
            'course_format' => $courseFormatText,
        ];

        // --- 培训记录（总体情况） ---
        $staffExamInfo = null;
        if ($planStaff->staff_exam_id) {
            $staffExamInfo = StaffExam::find($planStaff->staff_exam_id);
        }
        
        // 如果通过staff_exam_id没找到，尝试直接查询sj_staff_exam表
        if (!$staffExamInfo) {
            try {
                // 先尝试不加status条件查询
                $staffExamInfo = Db::table('sj_staff_exam')
                    ->where('plan_id', $plan_id)
                    ->where('staff_id', $staff_id)
                    ->order('create_time', 'desc') // 获取最新的考试记录
                    ->find();
                
                // 如果还是没找到，尝试只用staff_id查询（可能plan_id不匹配）
                if (!$staffExamInfo) {
                    $staffExamInfo = Db::table('sj_staff_exam')
                        ->where('staff_id', $staff_id)
                        ->order('create_time', 'desc')
                        ->find();
                }
                
                // 如果找到了记录，转换为对象以保持兼容性
                if ($staffExamInfo) {
                    $staffExamInfo = (object)$staffExamInfo;
                }
            } catch (Exception $e) {
                // 查询失败，保持$staffExamInfo为null
            }
        }

        // 安全处理数值
        $rawRequiredDuration = $planInfo->required_duration ?? '0';
        $requiredDuration = filter_var($rawRequiredDuration, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) ?? 0.0;
        
        $actualStudiedHours = $cumulativeHours; // 复用上面已安全处理的 $cumulativeHours

        $rawProgress = $planStaff->progress ?? '0';
        $progress = filter_var($rawProgress, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) ?? 0.0;
        
        // 考试成绩安全处理 - 修正字段名称
        $examScoreVal = 0.0;
        $reExamScoreVal = null; // 保持 null 如果不存在或无效

        if ($staffExamInfo) {
            // 使用point字段而不是score字段（根据表结构）
            $rawScore = $staffExamInfo->point ?? $staffExamInfo->score ?? '0';
            $examScoreVal = filter_var($rawScore, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) ?? 0.0;

            // 检查是否有补考成绩字段
            if (isset($staffExamInfo->re_score) && $staffExamInfo->re_score !== null) {
                 $rawReScore = $staffExamInfo->re_score;
                 $validatedReScore = filter_var($rawReScore, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);
                 if ($validatedReScore !== null) { // 只有当它是有效数字或可转换为0时才赋值
                    $reExamScoreVal = $validatedReScore;
                 }
            }
        }

        $archiveData['training_record_summary'] = [
            'course_name' => $planInfo->plan_name ?? '',
            'required_hours' => $requiredDuration,
//            'studied_hours' => floatval(number_format($actualStudiedHours, 1)),
            'studied_hours' => $studied_hours,
            'learning_progress_percentage' => floatval(number_format($progress, 2)),
            'completion_certificate_url' => $planStaff->complete_img_url ?? '',
            'exam_score' => $staffExamInfo ? floatval(number_format($examScoreVal, 2)) : null,
            'is_exam_passed' => $staffExamInfo ? ($staffExamInfo->exam_ret == 9 ? '合格' : '不合格') : null,
            'retake_exam_score' => $reExamScoreVal !== null ? floatval(number_format($reExamScoreVal, 2)) : null,
            'is_retake_exam_passed' => null, // 暂时设为null，因为表结构中没有明确的补考通过字段
        ];

        // --- 随机照片（抓拍） ---
        $randomPhotos = [];
        $snaps = Db::table('sj_snap')
                     ->where('staff_id', $staff_id)
                     ->where('plan_id', $plan_id)
                     ->where('type', 1) // 1:学习课件
                     ->order('create_time', 'desc')
                     ->limit(3) // 只要显示3张
                     ->select();

        if (!$snaps->isEmpty()) {
            foreach ($snaps as $snap) {
                $coursewareTitle = '';
                if (!empty($snap['courseware_id'])) {
                    $courseware = Db::table('sj_courseware')->where('id', $snap['courseware_id'])->find();
                    if ($courseware) {
                        $coursewareTitle = $courseware['title'];
                    }
                }
                $randomPhotos[] = [
                    'timestamp' => $this->formatDate($snap['create_time'], 'Y-m-d H:i:s'),
                    'image_url' => $snap['img_url'],
                    'courseware_name' => $coursewareTitle,
                ];
            }
        }
        $archiveData['random_photos'] = $randomPhotos;

        // --- 课程详细列表 ---
        $detailedCourses = [];
        $planCourses = PlanCourse::where('status', 1)->where('plan_id', $plan_id)->select();
        $courseIndex = 1;
        if (!$planCourses->isEmpty()) {
            foreach ($planCourses as $pc) {
                $course = Course::find($pc->course_id);

                $rawPcDuration = $pc->duration ?? '0';
                $duration = filter_var($rawPcDuration, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) ?? 0.0;
                
                $coursewaresData = [];
                
                // 调试：检查课程对象
                if ($course) {
                    // 方法1：尝试解析 ware_json
                    if (!empty($course->ware_json)) {
                        $decodedWareJson = null;
                        if (is_string($course->ware_json)) {
                            $decodedWareJson = json_decode($course->ware_json, true);
                            if (json_last_error() !== JSON_ERROR_NONE) {
                                // JSON解析失败，记录错误
                                $coursewaresData[] = [
                                    'title' => 'JSON解析错误: ' . json_last_error_msg(),
                                    'type' => 'debug',
                                    'duration' => 0,
                                    'lecturer' => '未知',
                                ];
                            }
                        } elseif (is_array($course->ware_json) || is_object($course->ware_json)) {
                            $decodedWareJson = (array)$course->ware_json;
                        }

                        if (is_array($decodedWareJson) && !empty($decodedWareJson)) {
                            // ware_json 存储的是课件ID数组，如 [34,33,32,31,30,29,28,27]
                            foreach ($decodedWareJson as $index => $wareId) {
                                // 确保是数字ID
                                $wareId = intval($wareId);
                                if ($wareId <= 0) continue;
                                
                                try {
                                    // 1. 通过课件ID在 sj_course_link_ware 表中查找对应的 courseware_id
                                    // ware_json 中的ID就是 sj_course_link_ware 表的主键
                                    $linkWare = Db::table('sj_course_link_ware')
                                        ->where('courseware_id', $wareId)
                                        ->where('course_id', $course->id)
                                        ->where('status', 1)
                                        ->find();

                                    if ($linkWare && !empty($linkWare['courseware_id'])) {
                                        // 2. 用 courseware_id 查询 sj_courseware 表获取课件详情
                                        $coursewareDetail = Db::table('sj_courseware')
                                            ->where('id', $linkWare['courseware_id'])
                                            ->where('status', 1)
                                            ->find();

                                        if ($coursewareDetail) {
                                            // 格式化时长（duration字段单位是分钟）
                                            $durationMinutes = intval($coursewareDetail['duration'] ?? 0);
                                            $hour = intval($coursewareDetail['hour'] ?? 0);
                                            $durationDisplay = $durationMinutes > 0 ? $durationMinutes  : '时长未设置';
                                            
                                            // 查询课件对应的讲师
                                            $lecturerName = '未分配讲师';
                                            if (!empty($coursewareDetail['teacher_id'])) {
                                                $teacher = Db::table('sj_teacher')->where('id', $coursewareDetail['teacher_id'])->find();
                                                if ($teacher) {
                                                    $lecturerName = $teacher['username'];
                                                }
                                            }
                                            
                                            $coursewaresData[] = [
                                                'title' => $coursewareDetail['title'] ?? ('课件' . ($index + 1)),
                                                'type' => $this->getCoursewareType($coursewareDetail),
                                                'duration' => $durationDisplay,
                                                'raw_duration' => $durationMinutes,
                                                'lecturer' => $lecturerName,
                                                'courseware_id' => $linkWare['courseware_id'],
                                                'link_ware_id' => $wareId,
                                                'hour' => $hour,
                                            ];
                                        } else {
                                            // courseware_id 对应的课件不存在
                                            $coursewaresData[] = [
                                                'title' => '课件详情未找到 (courseware_id: ' . $linkWare['courseware_id'] . ')',
                                                'type' => 'debug',
                                                'duration' => '时长未设置',
                                                'lecturer' => '未知',
                                                'raw_duration' => 0,
                                                'link_ware_id' => $wareId,
                                            ];
                                        }
                                    } else {
                                        // 在 sj_course_link_ware 表中没找到对应记录
                                        $coursewaresData[] = [
                                            'title' => '课件关联记录未找到 (link_ware_id: ' . $wareId . ')',
                                            'type' => 'debug',
                                            'duration' => '时长未设置',
                                            'lecturer' => '未知',
                                            'raw_duration' => 0,
                                            'link_ware_id' => $wareId,
                                        ];
                                    }
                                } catch (Exception $e) {
                                    $coursewaresData[] = [
                                        'title' => '查询课件时出错: ' . $e->getMessage(),
                                        'type' => 'error',
                                        'duration' => '时长未设置',
                                        'lecturer' => '未知',
                                        'raw_duration' => 0,
                                        'link_ware_id' => $wareId,
                                    ];
                                }
                            }
                        }
                    }
                    
                    // 方法2：如果ware_json没有数据，查询关联表
                    if (empty($coursewaresData)) {
                        try {
                            $linkedWares = Db::table('sj_course_link_ware')
                                ->where('course_id', $course->id)
                                ->select();
                            
                            if (!$linkedWares->isEmpty()) {
                                foreach ($linkedWares as $linkedWare) {
                                    $coursewareItem = Db::table('sj_courseware')
                                        ->where('id', $linkedWare['courseware_id'])
                                        ->find();
                                    
                                    if ($coursewareItem) {
                                        // 格式化时长（duration字段单位是分钟）
                                        $durationMinutes = intval($coursewareItem['duration'] ?? 0);
                                        $durationDisplay = $durationMinutes > 0 ? $durationMinutes . '分钟' : '时长未设置';
                                        
                                        // 查询课件对应的讲师
                                        $lecturerName = '未分配讲师';
                                        if (!empty($coursewareItem['teacher_id'])) {
                                            $teacher = Db::table('sj_teacher')->where('id', $coursewareItem['teacher_id'])->find();
                                            if ($teacher) {
                                                $lecturerName = $teacher['username'];
                                            }
                                        }
                                        
                                        $coursewaresData[] = [
                                            'title' => $coursewareItem['title'] ?? '课件标题未知',
                                            'type' => $this->getCoursewareType($coursewareItem),
                                            'duration' => $durationDisplay,
                                            'raw_duration' => $durationMinutes,
                                            'lecturer' => $lecturerName,
                                            'courseware_id' => $linkedWare['courseware_id'],
                                        ];
                                    }
                                }
                            }
                        } catch (Exception $e) {
                            $coursewaresData[] = [
                                'title' => '查询课件时出错: ' . $e->getMessage(),
                                'type' => 'error',
                                'duration' => 0,
                                'lecturer' => '未知',
                            ];
                        }
                    }
                    
                    // 方法3：如果还是没有数据，添加调试信息
                    if (empty($coursewaresData)) {
                        $coursewaresData[] = [
                            'title' => '未找到课件数据 (课程ID: ' . $course->id . ')',
                            'type' => 'debug',
                            'duration' => 0,
                            'lecturer' => '未知',
                        ];
                    }
                }
                $hours_sum = '';
                if ( !empty($coursewaresData) ) {
                    $hours_sum = array_sum(array_column($coursewaresData, 'hour'));
                }

//                dump($hours_sum);
//                die;
                $detailedCourses[] = [
                    'no' => $courseIndex++,
                    'content_name' => $course->course_name ?? '',
                    'hours' => $duration, 
                    'coursewares' => $coursewaresData,
                    'hours_sum' => $hours_sum,
                ];
                $archiveData['training_record_summary']['required_hours'] = $hours_sum;
            }
        }
        $archiveData['detailed_course_list'] = [
            'header_name' => $planInfo->plan_name ?? '',
            'list' => $detailedCourses
        ];

        // --- 考试试题详情 ---
        $examQuestionsDetails = [];
        if ($staffExamInfo) {
            // sj_staff_exam 表存储成绩，exam_json 不包含题目内容
            // 直接通过 exam_id 查询试卷和题目信息
            $examQuestionsDetails = $this->getExamQuestionsFromTables($staffExamInfo, [
                'staff_exam_id' => $staffExamInfo->id ?? 'null',
                'exam_id' => $staffExamInfo->exam_id ?? 'null',
                'total_score' => $staffExamInfo->all_total ?? 0,
                'exam_progress' => $staffExamInfo->exam_progress ?? 1,
                'exam_result' => $staffExamInfo->exam_ret ?? 1,
            ]);
        } else {
            $examQuestionsDetails[] = [
                'notice' => '未找到员工考试记录',
                'debug_info' => [
                    'plan_staff_id' => $plan_staff_id,
                    'plan_id' => $plan_id,
                    'staff_id' => $staff_id,
                    'staff_exam_id_from_plan_staff' => $planStaff->staff_exam_id ?? 'null',
                    'search_attempted' => [
                        'by_staff_exam_id' => !empty($planStaff->staff_exam_id),
                        'by_plan_and_staff_id' => true
                    ]
                ],
                'suggestion' => '可能该学员尚未参加考试，或考试记录存储方式不同'
            ];
        }
        $staff_answers = '';
        if ( !empty($staffExamInfo->exam_json) ) {
            $staff_answers = json_decode($staffExamInfo->exam_json, true);
        }

        if ( !empty($staff_answers) ) {
            $staff_answers = array_column($staff_answers, null, 'id');
            foreach ($examQuestionsDetails as $key => &$value) {
                if ( !empty($value['topic_id']) && !empty($staff_answers[$value['topic_id']]) ) {
                    $value['staff_answer'] = $staff_answers[$value['topic_id']]['selectAnswer']; // 答案
                    $value['is_correct'] = true;

                    // 答对 isRight = 2 答对,  isRight = 3 答错
                    if ( $staff_answers[$value['topic_id']]['isRight'] == 2 ) {
                        $value['score_obtained'] = $value['max_score'];
                    }

                    // 得分
//                    $correct_answer = json_decode($value['correct_answer'], true);
//                    //  判断单选题, 多选题
//                    if ( $value['type'] == '多选题' ) {
//
//                    } else {
//                        // 单项/判断
////                        if ( $value['correct_answer'] == $value['staff_answer'] ) {
//                        if ( in_array($value['staff_answer'], $correct_answer) ) {
//                            // 答对, 得分
//                            $value['score_obtained'] = $value['max_score'];
//                        }
//                    }

                }
            }
            unset($value);
        }

        $archiveData['exam_questions_details'] = $examQuestionsDetails;

        // --- 考试试卷名称 ---
        $examPaperName = '';
        if ($staffExamInfo && $staffExamInfo->exam_id) {
            try {
                $exam = Exam::find($staffExamInfo->exam_id);
                if ($exam && !empty($exam->exam_name)) {
                    $examPaperName = $exam->exam_name;
                } else {
                    $examPaperName = '试卷记录存在但名称为空 (exam_id: ' . $staffExamInfo->exam_id . ')';
                }
            } catch (Exception $e) {
                $examPaperName = '查询试卷时出错: ' . $e->getMessage();
            }
        } else {
            $examPaperName = '无有效考试信息 (staffExamInfo: ' . ($staffExamInfo ? 'exists' : 'null') . 
                           ', exam_id: ' . ($staffExamInfo->exam_id ?? 'null') . ')';
        }
        $archiveData['exam_paper_name'] = $examPaperName;

        // --- 考试详情摘要 ---
        $archiveData['exam_details_summary'] = [
            'class_name' => $archiveData['training_info']['training_name'],
            'examinee_name' => $archiveData['basic_info']['name'],
            'score' => $archiveData['training_record_summary']['exam_score'],
            'exam_submission_time' => $planStaff->exam_time ? $this->formatDate($planStaff->exam_time) : '-',
            'grader' => '系统判断',
        ];

        return app('json')->success($archiveData);
    }

    /**
     * 从数据库表获取考试题目详情的备用方法
     * @param object $staffExamInfo 员工考试信息
     * @param array $debugInfo 调试信息
     * @return array 题目详情数组
     */
    private function getExamQuestionsFromTables($staffExamInfo, $debugInfo)
    {
        $examQuestionsDetails = [];

        try {
            if (!$staffExamInfo || !$staffExamInfo->exam_id) {
                return [[
                    'notice' => '无有效的exam_id来获取题目',
                    'debug' => $debugInfo
                ]];
            }
            
            // 1. 获取试卷信息
            $exam = Db::table('sj_exam')->where('id', $staffExamInfo->exam_id)->find();
            if (!$exam) {
                return [[
                    'notice' => '未找到试卷记录 (exam_id: ' . $staffExamInfo->exam_id . ')',
                    'debug' => $debugInfo
                ]];
            }
            
            // 添加考试成绩摘要信息
            $examQuestionsDetails[] = [
                'exam_summary' => [
                    'exam_name' => $exam['exam_name'] ?? '未知试卷',
                    'total_score' => $staffExamInfo->all_total ?? 0,
                    'exam_status' => $staffExamInfo->exam_progress == 9 ? '已完成' : '进行中',
                    'exam_result' => $staffExamInfo->exam_ret == 9 ? '通过' : '未通过',
                    'exam_time' => $staffExamInfo->exam_time ?? 0,
                    'submit_time' => $staffExamInfo->submit_time ?? 0,
                    'use_time' => $staffExamInfo->use_time ?? 0,
                    'min_point' => $exam['min_point'] ?? 60,
                ]
            ];
            
            // 2. 从sj_exam_link_topic表获取试卷关联的所有题目ID
            $linkedTopics = Db::table('sj_exam_link_topic')
                ->where('exam_id', $staffExamInfo->exam_id)
                ->order('sort', 'asc')
                ->select();
            
            if ($linkedTopics->isEmpty()) {
                return [[
                    'notice' => '试卷中未找到任何关联题目',
                    'exam_info' => [
                        'exam_id' => $staffExamInfo->exam_id,
                        'exam_name' => $exam['exam_name'] ?? '未知试卷',
                    ],
                    'debug' => $debugInfo
                ]];
            }
            
            // 3. 收集所有题目ID
            $allTopicIds = [];
            foreach ($linkedTopics as $link) {
                $allTopicIds[] = intval($link['topic_id']);
            }
            
            // 4. 批量获取题目详情
            $topics = Db::table('sj_topic')
                ->whereIn('id', $allTopicIds)
                ->where('status', 1)
                ->select();
            
            if ($topics->isEmpty()) {
                return [[
                    'notice' => '未找到任何有效题目记录',
                    'topic_ids' => $allTopicIds,
                    'debug' => $debugInfo
                ]];
            }
            
            // 5. 解析学员答案（从exam_json中提取）
            $studentAnswers = [];
            if (!empty($staffExamInfo->exam_json)) {
                // 尝试从exam_json中提取学员答案
                $examData = is_string($staffExamInfo->exam_json) ? 
                    json_decode($staffExamInfo->exam_json, true) : 
                    (array)$staffExamInfo->exam_json;
                
                if (is_array($examData)) {
                    foreach ($examData as $item) {
                        if (isset($item['topic_id']) && isset($item['answer'])) {
                            $studentAnswers[$item['topic_id']] = $item['answer'];
                        }
                    }
                }
            }
            
            // 6. 构建题目详情
            foreach ($topics as $topic) {
                $topicType = '';
                switch ($topic['type']) {
                    case 1: $topicType = '单选题'; break;
                    case 2: $topicType = '多选题'; break;
                    case 3: $topicType = '判断题'; break;
                    default: $topicType = '未知题型(' . $topic['type'] . ')';
                }
                
                // 构建选项
                $options = [];
                if ($topic['type'] == 3) { // 判断题
                    $options = ['A' => '正确', 'B' => '错误'];
                } else { // 选择题
                    if (!empty($topic['a'])) $options['A'] = $topic['a'];
                    if (!empty($topic['b'])) $options['B'] = $topic['b'];
                    if (!empty($topic['c'])) $options['C'] = $topic['c'];
                    if (!empty($topic['d'])) $options['D'] = $topic['d'];
                    if (!empty($topic['e'])) $options['E'] = $topic['e'];
                    if (!empty($topic['f'])) $options['F'] = $topic['f'];
                }
                
                // 学员答案
                $staffAnswer = $studentAnswers[$topic['id']] ?? '';
                $correctAnswer = $topic['answer'] ?? '';
                $isCorrect = (strval($staffAnswer) === strval($correctAnswer));
                
                // 计算分数（基于题型和试卷设置）
                $maxScore = 0;
                $scoreObtained = 0;
                switch ($topic['type']) {
                    case 1: // 单选题
                        $maxScore = $exam['dan_point'] ?? 2;
                        break;
                    case 2: // 多选题
                        $maxScore = $exam['duo_point'] ?? 3;
                        break;
                    case 3: // 判断题
                        $maxScore = $exam['pan_point'] ?? 1;
                        break;
                }
                
                if ($isCorrect) {
                    $scoreObtained = $maxScore;
                }
                
                $examQuestionsDetails[] = [
                    'type' => $topicType,
                    'content' => $topic['title'] ?? '题目内容缺失',
                    'options' => $options,
                    'correct_answer' => $correctAnswer,
                    'staff_answer' => $staffAnswer,
                    'is_correct' => $isCorrect,
                    'score_obtained' => floatval($scoreObtained),
                    'max_score' => floatval($maxScore),
                    'topic_id' => $topic['id'], // 添加题目ID用于调试
                ];
            }
            
            // 如果没有学员答案，添加说明
            if (empty($studentAnswers)) {
                array_unshift($examQuestionsDetails, [
                    'notice' => '成功获取题目详情，但未找到学员答案记录',
                    'topics_count' => count($examQuestionsDetails) - 1, // 减去摘要信息
                    'debug' => $debugInfo
                ]);
            }
            
        } catch (Exception $e) {
            return [[
                'notice' => '获取题目详情时发生错误: ' . $e->getMessage(),
                'debug' => $debugInfo,
                'error_line' => $e->getLine(),
                'error_file' => basename($e->getFile())
            ]];
        }
        
        return $examQuestionsDetails;
    }

    /**
     * 下载学员培训档案PDF
     * GET enterprise/archive/download_pdf
     * @param Request $request
     * @return \\think\\Response
     */
    public function downloadPdf(Request $request)
    {
        $plan_staff_id = intval($request->param('plan_staff_id', 0));
        if (empty($plan_staff_id) || $plan_staff_id <= 0) {
            return app('json')->fail('计划人员ID (plan_staff_id) 无效');
        }

        // 1. 获取档案数据
        $archiveResponse = $this->getTrainingRecord($request);
        if ($archiveResponse->getCode() !== 200) {
            // 如果获取数据失败，直接返回JSON错误
            return $archiveResponse;
        }
        $archiveData = json_decode($archiveResponse->getContent(), true)['data'] ?? [];

        if (empty($archiveData)) {
            return app('json')->fail('获取档案数据失败或数据为空');
        }

        try {
            // 2. 生成HTML内容
            $htmlContent = $this->generateArchivePdfHtml($archiveData);

            // 3. 返回HTML内容供前端打印
            // 返回包含打印样式的完整HTML页面
            $fullHtml = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>学员培训档案</title>
    <style>
        @media print {
            body { margin: 0; }
            .no-print { display: none !important; }
        }
        @media screen {
            .print-only { display: none; }
            .no-print { 
                position: fixed; 
                top: 10px; 
                right: 10px; 
                z-index: 1000; 
                background: #007bff; 
                color: white; 
                padding: 10px 20px; 
                border: none; 
                border-radius: 5px; 
                cursor: pointer; 
            }
        }
    </style>
</head>
<body>
    <button class="no-print" onclick="window.print()">打印/下载PDF</button>
    ' . $htmlContent . '
    <script>
        // 页面加载完成后自动触发打印对话框
        window.onload = function() {
            // 可以取消注释下面这行来自动打印
            // window.print();
        };
    </script>
</body>
</html>';
            
            // 使用ThinkPHP的响应对象返回HTML，避免跨域问题
            return response($fullHtml)
                ->contentType('text/html; charset=utf-8')
                ->header([
                    'Access-Control-Allow-Origin' => '*',
                    'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
                    'Access-Control-Allow-Headers' => 'Content-Type, Authorization'
                ]);

        } catch (\Exception $e) {
            // 记录错误日志
            trace($e->getMessage() . '\n' . $e->getTraceAsString(), 'error');
            return app('json')->fail('生成PDF失败：' . $e->getMessage());
        }
    }

    /**
     * 生成学员档案PDF的HTML内容
     * @param array $data 档案数据
     * @return string HTML内容
     */
    private function generateArchivePdfHtml($data)
    {
        // 使用heredoc语法构建HTML，注意变量替换和HTML转义
        $html = <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>学员培训档案</title>
    <style>
        body { font-family: cid0jp, sans-serif; line-height: 1.6; margin: 0; padding: 0; font-size: 10px; }
        .container { padding: 20px; }
        h1, h2, h3, h4 { margin-bottom: 10px; font-weight: bold; }
        h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
        h2 { font-size: 16px; border-bottom: 1px solid #eee; padding-bottom: 5px; margin-top: 20px; }
        h3 { font-size: 14px; margin-top: 15px; }
        h4 { font-size: 12px; margin-top: 10px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 15px; font-size: 9px; }
        th, td { border: 1px solid #ccc; padding: 6px; text-align: left; vertical-align: top; }
        th { background-color: #f2f2f2; font-weight: bold; }
        .label { font-weight: bold; width: 120px; }
        .value { }
        .section { margin-bottom: 20px; page-break-inside: avoid; } /* 尝试避免在section内部断页 */
        .photo-gallery img { max-width: 150px; max-height: 150px; margin: 5px; border: 1px solid #ddd; }
        .certificate-img img { max-width: 100%; height: auto; margin-top: 10px; border: 1px solid #ddd; }
        .exam-questions td { word-wrap: break-word; word-break: break-all; }
        .page-break { page-break-after: always; }
        .small-text { font-size: 8px; }
        .indent { padding-left: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>学员培训档案</h1>

        <div class="section">
            <h2>基本信息</h2>
            <table>
                <tr>
                    <td class="label">档案编号:</td><td class="value">{$this->escapeHtml($data['file_number'] ?? '')}</td>
                    <td class="label">生成日期:</td><td class="value">{$this->escapeHtml($data['generation_date'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">平台名称:</td><td class="value">{$this->escapeHtml($data['platform_name'] ?? '')}</td>
                    <td class="label">姓名:</td><td class="value">{$this->escapeHtml($data['basic_info']['name'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">性别:</td><td class="value">{$this->escapeHtml($data['basic_info']['gender'] ?? '')}</td>
                    <td class="label">年龄:</td><td class="value">{$this->escapeHtml($data['basic_info']['age'] ?? '')}</td>
                </tr>
                 <tr>
                    <td class="label">照片:</td>
                    <td class="value" colspan="3">
                        <img src="{$this->escapeHtml($data['basic_info']['avatar'] ?? '')}" alt="学员头像" style="max-width:80px; max-height:100px; border:1px solid #ddd;" />
                    </td>
                </tr>
                <tr>
                    <td class="label">联系电话:</td><td class="value">{$this->escapeHtml($data['basic_info']['phone'] ?? '')}</td>
                    <td class="label">身份证号:</td><td class="value">{$this->escapeHtml($data['basic_info']['id_card_number'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">文化程度:</td><td class="value">{$this->escapeHtml($data['basic_info']['education'] ?? '')}</td>
                    <td class="label">职称:</td><td class="value">{$this->escapeHtml($data['basic_info']['job_title'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">所在部门:</td><td class="value">{$this->escapeHtml($data['basic_info']['department'] ?? '')}</td>
                    <td class="label">工种:</td><td class="value">{$this->escapeHtml($data['basic_info']['work_type'] ?? '')}</td>
                </tr>
                 <tr>
                    <td class="label">平台注册时间:</td><td class="value">{$this->formatDate($data['basic_info']['platform_registration_time'] ?? '', 'Y-m-d H:i:s')}</td>
                    <td class="label">累计学时:</td><td class="value">{$this->escapeHtml($data['basic_info']['cumulative_hours'] ?? '0')}小时</td>
                </tr>
                <tr>
                    <td class="label">单位名称:</td><td class="value" colspan="3">{$this->escapeHtml($data['basic_info']['company_name'] ?? '')}</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2>培训信息</h2>
            <table>
                <tr>
                    <td class="label">培训名称:</td><td class="value" colspan="3">{$this->escapeHtml($data['training_info']['training_name'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">培训周期:</td><td class="value">{$this->escapeHtml($data['training_info']['training_period'] ?? '')}</td>
                    <td class="label">学习时段:</td><td class="value">{$this->escapeHtml($data['training_info']['study_time_range'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">学习方式:</td><td class="value">{$this->escapeHtml($data['training_info']['study_method'] ?? '')}</td>
                    <td class="label">课程形式:</td><td class="value">{$this->escapeHtml($data['training_info']['course_format'] ?? '')}</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2>培训记录 (总体情况)</h2>
            <table>
                <tr>
                    <td class="label">课程名称:</td><td class="value" colspan="3">{$this->escapeHtml($data['training_record_summary']['course_name'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">规定学时:</td><td class="value">{$this->escapeHtml($data['training_record_summary']['required_hours'] ?? '0')}小时</td>
                    <td class="label">已学学时:</td><td class="value">{$this->escapeHtml($data['training_record_summary']['studied_hours'] ?? '0')}小时</td>
                </tr>
                <tr>
                    <td class="label">学习进度:</td><td class="value">{$this->escapeHtml($data['training_record_summary']['learning_progress_percentage'] ?? '0')}%</td>
                    <td class="label">考试成绩:</td><td class="value">{$this->formatScore($data['training_record_summary']['exam_score'])}</td>
                </tr>
                 <tr>
                    <td class="label">是否合格:</td><td class="value">{$this->escapeHtml($data['training_record_summary']['is_exam_passed'] ?? '')}</td>
                    <td class="label">补考成绩:</td><td class="value">{$this->formatScore($data['training_record_summary']['retake_exam_score'])}</td>
                </tr>
                <tr>
                    <td class="label">补考是否合格:</td><td class="value">{$this->escapeHtml($data['training_record_summary']['is_retake_exam_passed'] ?? '')}</td>
                    <td class="label"></td><td class="value"></td>
                </tr>
                <tr>
                    <td class="label">培训合格证:</td>
                    <td colspan="3">
HTML;
        if (!empty($data['training_record_summary']['completion_certificate_url'])) {
            $html .= '<img src="' . $this->escapeHtml($data['training_record_summary']['completion_certificate_url']) . '" alt="培训合格证" style="max-width:300px; border:1px solid #ddd;" />';
        } else {
            $html .= '<span>未上传</span>';
        }
        $html .= <<<HTML
                    </td>
                </tr>
            </table>
        </div>
HTML;

        if (!empty($data['detailed_course_list']['list'])) {
            $html .= <<<HTML
        <div class="section">
            <h2>详细课程列表 ({$this->escapeHtml($data['detailed_course_list']['header_name'] ?? '')})</h2>
            <table>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>培训内容名称</th>
                        <th>学时</th>
                    </tr>
                </thead>
                <tbody>
HTML;
            foreach ($data['detailed_course_list']['list'] as $course) {
                $html .= <<<HTML
                    <tr>
                        <td>{$this->escapeHtml($course['no'] ?? '')}</td>
                        <td>{$this->escapeHtml($course['content_name'] ?? '')}</td>
                        <td>{$this->escapeHtml($course['hours'] ?? '')}</td>
                    </tr>
HTML;
                if (!empty($course['coursewares'])) {
                    $html .= <<<HTML
                    <tr>
                        <td colspan="3" class="indent">
                            <h4>包含课件:</h4>
                            <table>
                                <thead>
                                    <tr>
                                        <th>课件标题</th>
                                        <th>类型</th>
                                        <th>时长</th>
                                        <th>讲师</th>
                                    </tr>
                                </thead>
                                <tbody>
HTML;
                    foreach ($course['coursewares'] as $ware) {
                         // 跳过调试信息或错误信息
                        if (isset($ware['type']) && in_array($ware['type'], ['debug', 'error'])) {
                            continue;
                        }
                        $html .= <<<HTML
                                    <tr>
                                        <td>{$this->escapeHtml($ware['title'] ?? '')}</td>
                                        <td>{$this->escapeHtml($ware['type'] ?? '')}</td>
                                        <td>{$this->escapeHtml($ware['duration'] ?? '')}</td>
                                        <td>{$this->escapeHtml($ware['lecturer'] ?? '')}</td>
                                    </tr>
HTML;
                    }
                    $html .= <<<HTML
                                </tbody>
                            </table>
                        </td>
                    </tr>
HTML;
                }
            }
            $html .= <<<HTML
                </tbody>
            </table>
        </div>
HTML;
        }


        if (!empty($data['random_photos'])) {
            $html .= <<<HTML
        <div class="section photo-gallery">
            <h2>随机抓拍照片</h2>
            <table>
                <thead>
                    <tr>
                        <th>抓拍时间</th>
                        <th>照片</th>
                        <th>学习课件</th>
                    </tr>
                </thead>
                <tbody>
HTML;
            foreach ($data['random_photos'] as $photo) {
                $html .= <<<HTML
                    <tr>
                        <td>{$this->escapeHtml($photo['timestamp'] ?? '')}</td>
                        <td><img src="{$this->escapeHtml($photo['image_url'] ?? '')}" alt="抓拍照片" /></td>
                        <td>{$this->escapeHtml($photo['courseware_name'] ?? '')}</td>
                    </tr>
HTML;
            }
            $html .= <<<HTML
                </tbody>
            </table>
        </div>
HTML;
        }

        $html .= <<<HTML
        <div class="section">
            <h2>考试详情</h2>
            <h4>试卷名称: {$this->escapeHtml($data['exam_paper_name'] ?? '无')}</h4>
            <table>
                <tr>
                    <td class="label">培训班名称:</td><td class="value">{$this->escapeHtml($data['exam_details_summary']['class_name'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">考生姓名:</td><td class="value">{$this->escapeHtml($data['exam_details_summary']['examinee_name'] ?? '')}</td>
                </tr>
                <tr>
                    <td class="label">考试得分:</td><td class="value">{$this->formatScore($data['exam_details_summary']['score'])}</td>
                </tr>
                <tr>
                    <td class="label">交卷时间:</td><td class="value">{$this->escapeHtml($data['exam_details_summary']['exam_submission_time'] ?? '')}</td>
                </tr>
                 <tr>
                    <td class="label">阅卷人:</td><td class="value">{$this->escapeHtml($data['exam_details_summary']['grader'] ?? '')}</td>
                </tr>
            </table>
HTML;

        if (!empty($data['exam_questions_details']) && is_array($data['exam_questions_details'])) {
            $examSummary = [];
            $actualQuestions = [];

            foreach ($data['exam_questions_details'] as $detail) {
                if (isset($detail['exam_summary'])) {
                    $examSummary = $detail['exam_summary'];
                } elseif (isset($detail['type'])) { // 假定包含'type'字段的是实际题目
                    $actualQuestions[] = $detail;
                }
            }
            
            if (!empty($examSummary)) {
                 $html .= <<<HTML
            <h4>考试摘要</h4>
            <table>
                <tr><td class="label">试卷名称:</td><td>{$this->escapeHtml($examSummary['exam_name'] ?? '')}</td></tr>
                <tr><td class="label">总分:</td><td>{$this->escapeHtml($examSummary['total_score'] ?? '')}</td></tr>
                <tr><td class="label">考试状态:</td><td>{$this->escapeHtml($examSummary['exam_status'] ?? '')}</td></tr>
                <tr><td class="label">考试结果:</td><td>{$this->escapeHtml($examSummary['exam_result'] ?? '')}</td></tr>
                <tr><td class="label">考试时长:</td><td>{$this->escapeHtml($examSummary['exam_time'] ?? '')} 分钟</td></tr>
                <tr><td class="label">提交时间:</td><td>{$this->formatDate($examSummary['submit_time'] ?? 0, 'Y-m-d H:i:s')}</td></tr>
                <tr><td class="label">用时:</td><td>{$this->escapeHtml($examSummary['use_time'] ?? '')} 秒</td></tr>
                <tr><td class="label">合格分数:</td><td>{$this->escapeHtml($examSummary['min_point'] ?? '')}</td></tr>
            </table>
HTML;
            }


            if (!empty($actualQuestions)) {
                $html .= <<<HTML
            <h3>考试题目详情</h3>
            <table class="exam-questions">
                <thead>
                    <tr>
                        <th>题型</th>
                        <th>题目内容</th>
                        <th>选项</th>
                        <th>正确答案</th>
                        <th>学员答案</th>
                        <th>是否正确</th>
                        <th>得分/满分</th>
                    </tr>
                </thead>
                <tbody>
HTML;
                foreach ($actualQuestions as $question) {
                    $optionsHtml = '';
                    if (!empty($question['options']) && is_array($question['options'])) {
                        foreach ($question['options'] as $key => $value) {
                            $optionsHtml .= "<div><strong>{$this->escapeHtml($key)}:</strong> {$this->escapeHtml($value)}</div>";
                        }
                    } else {
                        $optionsHtml = '无选项';
                    }
                    $isCorrectText = ($question['is_correct'] ?? false) ? '正确' : '错误';
                    $scoreText = ($question['score_obtained'] ?? '0') . '/' . ($question['max_score'] ?? '0');

                    $html .= <<<HTML
                    <tr>
                        <td>{$this->escapeHtml($question['type'] ?? '')}</td>
                        <td>{$this->escapeHtml($question['content'] ?? '')}</td>
                        <td>{$optionsHtml}</td>
                        <td>{$this->escapeHtml($question['correct_answer'] ?? '')}</td>
                        <td>{$this->escapeHtml($question['staff_answer'] ?? '')}</td>
                        <td>{$isCorrectText}</td>
                        <td>{$scoreText}</td>
                    </tr>
HTML;
                }
                $html .= <<<HTML
                </tbody>
            </table>
HTML;
            } elseif (isset($data['exam_questions_details'][0]['notice'])) {
                // 显示提示信息，如果题目列表为空但有notice
                $html .= "<p>" . $this->escapeHtml($data['exam_questions_details'][0]['notice']) . "</p>";
            }
        } else {
            $html .= "<p>无考试题目详情。</p>";
        }
        $html .= <<<HTML
        </div>
    </div>
</body>
</html>
HTML;
        return $html;
    }

    /**
     * 辅助函数：HTML特殊字符转义
     * @param string|null $string
     * @return string
     */
    private function escapeHtml($string)
    {
        return htmlspecialchars((string)$string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
    
    /**
     * 辅助函数：格式化分数，处理null和空值
     * @param mixed $score
     * @return string
     */
    private function formatScore($score)
    {
        if ($score === null || $score === '') {
            return '未考试';
        }
        $floatScore = filter_var($score, FILTER_VALIDATE_FLOAT);
        if ($floatScore === false) {
            return '无效分数';
        }
        return number_format($floatScore, 1);
    }

} 